﻿package com.eve.eplus.main;

import java.text.SimpleDateFormat;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

import com.eve.eplus.R;
import com.eve.eplus.common.activity.BaseActivity;
import com.eve.eplus.common.activity.StartActivity;
import com.eve.eplus.common.app.BaseApplication;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.common.view.ComToastTools;
import com.eve.eplus.sns.SNSAccountManager;
import com.eve.eplus.sns.weibo.AccessTokenKeeper;
import com.eve.eplus.sns.weibo.UsersAPIDef;
import com.eve.eplus.sns.weibo.WeiboAPIGather;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;

/**
 * 帐号绑定界面 本页面负责绑定各个平台的帐号
 * 
 * @author Norsie
 * @create 12-11-29
 */
public class BindingActivity extends BaseActivity {

	private Context mContext = BindingActivity.this;
	private Weibo mSinaWeibo;
	private LinearLayout sinaBtn;
	private String target; // 目标Activity
	private String source; // 来源Activity
	HashMap<String, String> map = new HashMap<String, String>();

	SsoHandler mSinaSsoHandler; // 新浪微博SSO Handler

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login_main);
		initWeibo();
		target = getIntent().getStringExtra(Constants.ACTIVITY_TARGET);
		source = getIntent().getStringExtra(Constants.ACTIVITY_SOURCE);
	}

	/**
	 * 新浪微博绑定功能初始化
	 */
	private void initWeibo() {
		// TODO Auto-generated method stub
		mSinaWeibo = Weibo.getInstance(Constants.SINA_CONSUMER_KEY,
				Constants.SINA_REDIRECT_URL);
		sinaBtn = (LinearLayout) findViewById(R.id.btn_sina);// 触发sso的按钮
		// //检查是否支持Sso
		// try {
		// Class sso = Class.forName("com.weibo.sdk.android.sso.SsoHandler");
		// } catch (ClassNotFoundException e) {
		// LogTools.info("com.weibo.sdk.android.sso.SsoHandler not found");
		//
		// }
		sinaBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSinaSsoHandler = new SsoHandler(BindingActivity.this,
						mSinaWeibo);
				mSinaSsoHandler.authorize(new AuthDialogListener());
			}
		});

	}

	/**
	 * SSO认证回调
	 * 
	 * @author norsie
	 * 
	 */
	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {

			LogTools.info(values.toString());
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid = values.getString("uid");
			String username= values.getString("userName");  //这里有个bug，用户昵称获取问题，新浪的sso和对话框不一致

			// 判断当前帐号是否已经存在
			if (SNSAccountManager.getAcountByToken(token,
					Constants.SNSTYPE_SINA) == null) {
				// 设置获取到的Token
				BaseApplication.sinaAccessToken = new Oauth2AccessToken(token,
						expires_in);
				if (BaseApplication.sinaAccessToken.isSessionValid()) {
					String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
							.format(new java.util.Date(
									BaseApplication.sinaAccessToken
											.getExpiresTime()));
					LogTools.info("认证成功: access_token: " + token + "  "
							+ "expires_in: " + expires_in + "  有效期：" + date);
					ComToastTools.ShowMsg(mContext, "授权成功", "s");

					map.put(Constants.ACCESS_TOKEN, token);
					map.put(Constants.EXPIRES_IN, expires_in);
					map.put(Constants.OVERTIME, date);
					map.put(Constants.SNS_UID, uid);
					map.put(Constants.SNSTYPE, Constants.SNSTYPE_SINA);
					map.put(Constants.SNS_ACCOUNT_NAME, username);
					map.put(Constants.SNS_ACCOUNT_INDEX, "1");
					SNSAccountManager.save(map);
					map.clear();
					BaseApplication.SNS_ACCOUNT = SNSAccountManager
							.getAccountList();
					// 页面的跳转
					if (target == null)
						// 检查是否为第一次登陆绑定
						if (!BaseApplication.isFirst) {
							Intent intent = new Intent(mContext,
									AccountManagerActivity.class);
							intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
							gotoActivityAndFinish(mContext, intent);
						} else
							// 跳到主页
							gotoActivityAndFinish(mContext, HomeActivity.class);
					else if (target
							.equals(Constants.ACTIVITY_TARGET_HOMEACTIVITY))
						// 跳到主页
						gotoActivityAndFinish(mContext, HomeActivity.class);
				}
			} else {
				ComToastTools.ShowMsg(mContext, "帐号已存在！", "l");
			}
		}

		@Override
		public void onError(WeiboDialogError e) {
			LogTools.error("Auth error : " + e.getMessage());
			ComToastTools.ShowMsg(mContext, "认证错误。(" + e.getMessage() + ")",
					"l");
		}

		@Override
		public void onCancel() {
			LogTools.info("Auth cancel");
			ComToastTools.ShowMsg(mContext, "认证被取消", "l");
		}

		@Override
		public void onWeiboException(WeiboException e) {
			LogTools.error("Auth exception : " + e.getMessage());
			ComToastTools.ShowMsg(mContext, "认证错误。(" + e.getMessage() + ")",
					"l");
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		/**
		 * SSO 句柄
		 */
		if (mSinaSsoHandler != null) {
			mSinaSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}

	}

	@Override
	public void onBackPressed() {
		if (source != null) {
			if (source.equals(Constants.ACTIVITY_SOURCE_ACCOUNTACTIVITY))
				super.onBackPressed();
		} else {
			// 退出程序
			BaseApplication.isExit = true;
			Intent intent = new Intent();
			intent.setClass(mContext, StartActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 清空栈
			startActivity(intent);
		}
	}

}
